package com.ifonly.activerecord;

import com.ifonly.activerecord.exceptions.ActiveRecordException;
import com.ifonly.utils.AopUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-18 13:57
 * @since JDK 1.6
 */
public class TableMapper {

    /*
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ single instance

    private TableMapper() {}

    private static class InstanceHolder {
        private static TableMapper instance = new TableMapper();
    }

    public static TableMapper getInstance() {
        return InstanceHolder.instance;
    }

    */

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 类与表的映射

    private Map<Class<? extends Model>, Table> tableMapping = new HashMap<Class<? extends Model>, Table>();


    public void addTableMapper(Class<? extends Model> clazz, Table table) {
        if (tableMapping.get(clazz) != null) {
            throw new ActiveRecordException("Model["+ clazz.getName() +"] has mapped");
        }

        tableMapping.put(clazz, table);
    }

    public Table getTable(Class<? extends Model> clazz) {
        if (AopUtils.isCglibClass(clazz)) {
            clazz = AopUtils.getCglibProxyTargetClass(clazz);
        }
        return tableMapping.get(clazz);
    }

}
